// Copyright 2023 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "CaeImeControl.h"
#include "../cae_service/CaeParamStorage.h"

CaeImeControl &CaeImeControl::GetInstance()
{
    static CaeImeControl instance;
    return instance;
}

CaeImeControl::CaeImeControl()
{
    mImeClient = new (std::nothrow) CaeImeClient();
    mClientType = CLIENT_PLATFORM_TYPE_MAX;
}

CaeImeControl::~CaeImeControl()
{
    if (mImeClient != nullptr) {
        delete mImeClient;
        mImeClient = nullptr;
    }
}

bool CaeImeControl::EnableRemoteIme(std::string clientType)
{
    if (mImeClient == nullptr) {
        mImeClient = new (std::nothrow) CaeImeClient();
        if (mImeClient == nullptr) {
            LOGE("Failed to init CaeImeClient");
            return false;
        }
    }

    mClientType = std::stoi(clientType);
    mImeClient->SetClientType(mClientType);
    mImeClient->StartProcess();
    return true;
}

bool CaeImeControl::IsNeedSetDefaultInputMethod()
{
    if (mClientType == ClientPlatformType::PLATFORM_ANDROID) {
        return true;
    }
    return false;
}

void CaeImeControl::DisableRemoteIme()
{
    if (mImeClient != nullptr) {
        mImeClient->StopProcess();
        mImeClient = nullptr;
    }
}

void CaeImeControl::SetDefaultInputMethod()
{
    signal(SIGCHLD, SIG_DFL);
    int ret = system("ime enable com.huawei.cloudphoneime/.CaeImeService");
    if (ret != 0) {
        LOGE("Failed to enable cloud phone ime.");
        return;
    }
    ret = system("ime set com.huawei.cloudphoneime/.CaeImeService");
    if (ret != 0) {
        LOGE("Failed to set cloud phone ime.");
        return;
    }
    signal(SIGCHLD, SIG_IGN);
    LOGI("Success to enable remote ime.");
}

void CaeImeControl::DisableDefaultInputMethod()
{
    signal(SIGCHLD, SIG_DFL);
    int ret = system("ime disable com.huawei.cloudphoneime/.CaeImeService");
    if (ret != 0) {
        LOGE("Failed to disable cloud phone ime.");
    }
    signal(SIGCHLD, SIG_IGN);
    LOGI("End to disable remote ime.");
}